package com.ntd.study.pro.zx.cbpp;

import com.ntd.study.pro.zx.wlpt.TestClient;
import org.apache.commons.io.IOUtils;
import org.dom4j.DocumentHelper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;


public class SendMsg {
    public static void main(String[] args) throws Exception{
        sendMsg("S0001");
    }

    public static void sendMsg(String code) throws UnsupportedEncodingException {

        MsgLoader msgLoader=new MsgLoader(code);
        byte[] msg=msgLoader.loadReqMsg();
        byte[] msgHead=("010109317 010190048140080010190048140080TPCG    "+String.format("%15s", code)).getBytes();
        byte[] msgLen= (String.format("%08d",msgHead.length + msg.length)).getBytes();
        byte[] send=new byte[71+msg.length];
        System.arraycopy(msgLen,0,send,0,8);
        System.arraycopy(msgHead,0,send,8,63);
        System.arraycopy(msg,0,send,71,msg.length);
        String address=CfgLoader.properties.getProperty("REMOTE_ADDRESS");
        String jksFile=CfgLoader.properties.getProperty("JKSFILE");
        byte[] result=null;
        try {
            //实际商户在外网环境使用时，请注释send方法，使用TestClient类的TestServer方法
//            result=send(send);
            result = TestClient.getInstance().TestServer(address,jksFile,msg);
            System.out.println("================完整响应报文为："+new String(result,"GBK"));
            String respMsgHead=DocumentHelper.parseText((new String(result,"GBK"))).asXML();
            String tranCode=DocumentHelper.parseText(respMsgHead).getRootElement().element("trancode").getText();
            String encryptRespMsgBody=DocumentHelper.parseText(respMsgHead).getRootElement().element("encrypt").getText();
            String signRespMsgBody=DocumentHelper.parseText(respMsgHead).getRootElement().element("signature").getText();
            System.out.println("================加密响应报文体为："+encryptRespMsgBody);
            byte[] respMsgBody=RSAUtil.decrypt(RSAUtil.getMerPrivateKey(),encryptRespMsgBody);
            System.out.println("================响应报文体解密为："+(new String(respMsgBody,"GBK")));
            System.out.println("================响应报文体验签结果为："+RSAUtil.verify(RSAUtil.getCITICPublicKey(),respMsgBody,signRespMsgBody));
            if ("B0002".equals(tranCode)||"D0001".equals(tranCode)||"T0001".equals(tranCode)){
                String batResultFile=DocumentHelper.parseText(new String(respMsgBody,"GBK")).getRootElement().element("body").element("resultFileContent").getText();
                System.out.println("================["+tranCode+"]交易的结果文件明细为："+Utils.unzip(batResultFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 内网测试专用方法，行外网络环境请是用TestClient类的TestServer方法发送报文
     */
    public final static byte[] send(byte[] message) throws Exception {
        Socket socket = null;
        byte[] returnbody = null;
        try {
            // 银联代付内网调试请输入银联代付应用IP和端口
            socket = new Socket("8.8.8.8",65525);
            socket.setSoTimeout(60000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 发送报文信息
        try {
            IOUtils.write(message, socket.getOutputStream());
        } catch (IOException e) {
            // 关闭连接
            IOUtils.closeQuietly(socket);
        }

        try {
            int heardlen = 8;
            byte returnheard[] = null;
            returnheard = new byte[heardlen];
            IOUtils.readFully(socket.getInputStream(), returnheard);
            int bodylen = Integer.parseInt(new String(returnheard));
            returnbody = new byte[bodylen];
            IOUtils.readFully(socket.getInputStream(), returnbody);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(socket);
        }
        return returnbody;
    }
}
